import type { App } from 'vue'
import useSettingsStore from '@/store/modules/settings'

const settingsStore = useSettingsStore()
export default function directive(app: App) {
  // 注册 v-auth 和 v-auth-all 指令
  app.directive('auth', {
    mounted: (el, binding) => {
      if (!useAuth().auth(binding.value)) {
        el.remove()
      }
    },
  })
  app.directive('auth-all', {
    mounted: (el, binding) => {
      if (!useAuth().authAll(binding.value)) {
        el.remove()
      }
    },
  })

  app.directive('auto-height', {
    mounted: (el, binding) => {
      const callback = (entries: any[]) => {
        entries.forEach((entry: any) => {
          if (entry.isIntersecting) {
            calcHeight()
          }
        })
      }
      const observer = new IntersectionObserver(callback)
      observer.observe(el)
      function calcHeight() {
        nextTick(() => {
          if (!el) {
            observer && observer.disconnect()
            window.removeEventListener('resize', calcHeight)
          }
          const footHeight = binding.value || 0
          const top = el.getBoundingClientRect().top
          const windowHeight = window.innerHeight
          const companyHeight = settingsStore.settings.copyright.enable ? 52 : 0
          const height = windowHeight - top - footHeight - companyHeight
          el.style.height = `${height}px`
        })
      }
      window.addEventListener('resize', calcHeight)
    },
  })
}
